#!/usr/bin/env python3
"""
TodoList 应用最终打包脚本
PyWebview Desktop Application Builder

使用方法:
    python build_todolist.py

功能:
    - 自动检查依赖
    - 创建应用图标
    - 修复主程序文件
    - 执行 PyInstaller 打包
    - 清理临时文件
"""

import os
import sys
import subprocess
import shutil
from pathlib import Path

def check_dependencies():
    """检查必要的依赖包"""
    print("🔍 检查依赖包...")
    required_packages = ['pyinstaller', 'pywebview', 'Pillow']
    missing_packages = []
    
    for package in required_packages:
        try:
            __import__(package)
            print(f"  ✅ {package}")
        except ImportError:
            missing_packages.append(package)
            print(f"  ❌ {package}")
    
    if missing_packages:
        print(f"\n⚠️  缺少依赖包: {', '.join(missing_packages)}")
        print("请运行: pip install pyinstaller pywebview Pillow")
        return False
    
    print("✅ 所有依赖包已安装")
    return True

def create_icon():
    """创建应用图标"""
    print("\n🎨 创建应用图标...")
    try:
        from PIL import Image, ImageDraw, ImageFont
        
        # 创建图标
        size = (256, 256)
        image = Image.new('RGBA', size, (52, 152, 219, 255))  # 蓝色背景
        draw = ImageDraw.Draw(image)
        
        # 绘制圆角矩形背景
        margin = 20
        draw.rounded_rectangle(
            [margin, margin, size[0]-margin, size[1]-margin],
            radius=30,
            fill=(41, 128, 185, 255)
        )
        
        # 绘制复选框图标
        check_size = 60
        check_x = (size[0] - check_size) // 2
        check_y = (size[1] - check_size) // 2 - 20
        
        # 复选框框架
        draw.rectangle(
            [check_x, check_y, check_x + check_size, check_y + check_size],
            outline=(255, 255, 255, 255),
            width=6,
            fill=None
        )
        
        # 对勾
        draw.line([check_x + 15, check_y + 30, check_x + 25, check_y + 40], fill=(255, 255, 255, 255), width=8)
        draw.line([check_x + 25, check_y + 40, check_x + 45, check_y + 20], fill=(255, 255, 255, 255), width=8)
        
        # 保存多种尺寸
        icon_path = "app.ico"
        sizes = [(16, 16), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)]
        images = []
        
        for icon_size in sizes:
            resized = image.resize(icon_size, Image.Resampling.LANCZOS)
            images.append(resized)
        
        images[0].save(icon_path, format='ICO', sizes=[img.size for img in images], append_images=images[1:])
        print(f"  ✅ 图标已创建: {icon_path}")
        return True
        
    except Exception as e:
        print(f"  ❌ 图标创建失败: {e}")
        return False

def create_fixed_main():
    """创建修复版本的主程序文件"""
    print("\n🔧 创建修复版本的主程序...")
    
    fixed_main_content = '''import webview
import sys
import os
from pathlib import Path
from todo_backend import api
from config import APP_CONFIG

def get_static_path():
    """获取静态文件路径，支持开发和打包环境"""
    if getattr(sys, 'frozen', False):
        # 打包后的环境
        base_path = Path(sys.executable).parent
        static_path = base_path / "_internal" / "static"
        if not static_path.exists():
            static_path = base_path / "static"
    else:
        # 开发环境
        static_path = Path(__file__).parent / "static"
    
    return str(static_path)

def main():
    """主函数"""
    static_path = get_static_path()
    html_path = os.path.join(static_path, "index.html")
    
    if not os.path.exists(html_path):
        print(f"错误: 找不到HTML文件: {html_path}")
        return
    
    # 创建窗口
    window = webview.create_window(
        title=f"TodoList {APP_CONFIG['VERSION']}",
        url=html_path,
        width=1200,
        height=800,
        min_size=(800, 600),
        resizable=True
    )
    
    # 启动应用
    webview.start(api=api)

if __name__ == "__main__":
    main()
'''
    
    try:
        with open("main_build.py", "w", encoding="utf-8") as f:
            f.write(fixed_main_content)
        print("  ✅ 修复版本主程序已创建: main_build.py")
        return True
    except Exception as e:
        print(f"  ❌ 创建主程序失败: {e}")
        return False

def build_application():
    """执行 PyInstaller 打包"""
    print("\n📦 开始打包应用...")
    
    # PyInstaller 命令（移除 --add-data=data;data，让应用自动创建数据目录）
    cmd = [
        "pyinstaller",
        "--name=TodoList",
        "--noconsole",
        "--onedir",
        "--add-data=static;static",
        "--add-data=config.py;.",
        "--hidden-import=webview",
        "--hidden-import=webview.platforms.winforms",
        "--hidden-import=webview.platforms.edgechromium", 
        "--hidden-import=bottle",
        "--icon=app.ico",
        "main_build.py"
    ]
    
    try:
        print(f"  执行命令: {' '.join(cmd)}")
        result = subprocess.run(cmd, check=True, capture_output=True, text=True)
        print("  ✅ 打包成功!")
        return True
    except subprocess.CalledProcessError as e:
        print(f"  ❌ 打包失败: {e}")
        print(f"  错误输出: {e.stderr}")
        return False

def cleanup():
    """清理临时文件"""
    print("\n🧹 清理临时文件...")
    
    cleanup_items = [
        "main_build.py",
        "TodoList.spec",
        "build",
        "__pycache__"
    ]
    
    for item in cleanup_items:
        try:
            if os.path.isfile(item):
                os.remove(item)
                print(f"  ✅ 删除文件: {item}")
            elif os.path.isdir(item):
                shutil.rmtree(item)
                print(f"  ✅ 删除目录: {item}")
        except Exception as e:
            print(f"  ⚠️  清理 {item} 失败: {e}")

def main():
    """主执行流程"""
    print("🚀 TodoList 应用打包工具")
    print("=" * 50)
    
    # 检查依赖
    if not check_dependencies():
        sys.exit(1)
    
    # 创建图标
    if not create_icon():
        print("⚠️  图标创建失败，但继续打包...")
    
    # 创建修复版主程序
    if not create_fixed_main():
        print("❌ 无法创建修复版主程序")
        sys.exit(1)
    
    # 执行打包
    if not build_application():
        print("❌ 打包失败")
        cleanup()
        sys.exit(1)
    
    # 清理临时文件
    cleanup()
    
    # 完成信息
    print("\n" + "=" * 50)
    print("🎉 打包完成!")
    print("📁 可执行文件位置: dist/TodoList/TodoList.exe")
    print("💡 提示: 整个 dist/TodoList 文件夹可以打包分发")
    print("=" * 50)

if __name__ == "__main__":
    main()
